<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 新版班牌接口
class Brand_api_v2 extends BaseController {

	public function __construct() {
        parent::__construct();
    }


    // 获取班牌首页信息接口
    public function get_class_data($brandId = 0){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('configModel');
        $this->load->model('staffModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));

        // // 授权码
        // $encryptStr = $this->get('encrypt_str');
        // if(empty($brandInfo['license_code_address']) || empty($encryptStr)) {
        //     exit(json("未授权，请联系管理员", false));
        // }
        // if($brandInfo['license_code_address'] != $encryptStr) {
        //     exit(json("授权码错误，请联系管理员", false));
        // }


        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
        if($classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');

        // 班级相册，首页推荐
        $albumParams['classId'] = $classInfo['id'];
        $albumParams['recommend'] = 1;
        $albumList = $this->contentModel->get_album($albumParams);
        $albumArray = array();
        foreach($albumList as $image) {
            $albumArray[] = array(
                "imageLink" => $image['image_link'],
                "imageDesc" => $image['image_desc']
            );
        }

        // 获取前10条班级通知
        $notifyParams['isDelete'] = 0;
        $notifyParams['classId'] = $brandInfo['class_id'];
        $notifyParams['pageStart'] = 0;
        $notifyParams['pageSize'] = 10;
        $notifyParams['field'] = 'id, notify_title as title, updatetime as time, notify_type as notifyType, external_link as externalLink, notify_urgent as notifyUrgent, urgent_endtime as urgentEndtime, is_top as isTop';
        $notifyParams['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $notifyParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $notifys = $this->contentModel->get_notify_list($notifyParams);
        // 获取前10条班级动态
        $newsParams['isDelete'] = 0;
        $newsParams['classId'] = $brandInfo['class_id'];
        $newsParams['pageStart'] = 0;
        $newsParams['pageSize'] = 10;
        $newsParams['field'] = 'id, news_title as title, updatetime as time';
        $newsParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $news = $this->contentModel->get_news_list($newsParams);

        // 获取前10条校园公告
        $announceParams['schoolId'] = $brandInfo['school_id'];
        $announceParams['isDelete'] = 0;
        $announceParams['pageStart'] = 0;
        $announceParams['pageSize'] = 10;
        $announceParams['field'] = 'id, announce_title as title, updatetime as time, announce_type as announceType, external_link as externalLink, is_top as isTop';
        $announceParams['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $announceParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $announces = $this->contentModel->get_announce_list($announceParams);

        // 返回值
        $ret['className'] = $classInfo['class_name'];

        // 班级名称限制最长46个字符
        if(strlen($ret['className']) > 46) {
            $ret['className'] = substr($ret['className'], 0, 46) . '...';
        }
        

        // 班徽
        $ret['classImg'] = $classInfo['class_logo'] ? $classInfo['class_logo'] : get_sys_img('class.jpg');

        // 班级格言
        $ret['classSlogan'] = $classInfo['class_slogan'] ? $classInfo['class_slogan'] : '';
        // 班级口号
        $ret['classWord'] = $classInfo['class_word'] ? $classInfo['class_word'] : '';
        $ret['classContent'] = trim_link_tags($classInfo['class_content']);
        // 首页推荐图片
        $ret['albumList'] = $albumArray;
        // 本月之星
        $ret['classStar'] = '';
        if (null !== $classInfo['class_star']) {
            $student = $this->schoolModel->get_student_info($classInfo['class_star']);
            if (isset($student['realname'])) {
                $ret['classStar'] = $student['realname'];
            } 
        }
        // 年级之星
        $ret['gradeStar'] = array();
        if (null !== $classInfo['grade_star']) {
            $teacherIdArr = explode(',', $classInfo['grade_star']);
            $teacherArr = array();
            foreach($teacherIdArr as $teacherId) {
                $teacher = $this->schoolModel->get_teacher_info($teacherId);
                $arr = array(
                    'id' => $teacher['id'],
                    'realname' => $teacher['realname'],
                    'headimgurl' => $teacher['headimgurl']
                );
                array_push($teacherArr, $arr);
            }
            if($teacherArr) {
                $ret['gradeStar'] = $teacherArr;
            }
        }

        // 获取班主任信息
        // $masterCoach = $this->staffModel->get_master_coach_by_class($classInfo['id']);
        $masterCoachs = $this->staffModel->get_master_coachs_by_class($classInfo['id']);
        $masterNameStr = '';
        $masterNameArr = array();
        if($masterCoachs) {
            $masterCoach = $masterCoachs[0];
            $masterInfo = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
            foreach($masterCoachs as $item) {
                $masterUserInfo = $this->schoolModel->get_school_user_info_realname($item['teacher_id']);
                if(!in_array($masterUserInfo['realname'], $masterNameArr)) {
                    $masterNameArr[] = $masterUserInfo['realname'];
                }
            }
            $masterNameStr = implode('、', $masterNameArr);
        } else {
            $masterInfo = NULL;
        }
        // 班主任
        $ret['classMaster'] = (object)null;;
        if(!empty($masterInfo)){
            $ret['classMaster'] = array(
                "name" => count($masterCoachs) == 1 ? $masterInfo['realname'] : $masterNameStr,
                "headimgurl" => count($masterCoachs) == 1 ? $masterInfo['headimgurl'] : get_sys_img('woman.jpg'),
                "mobile" => $masterInfo['mobile'],
                "message" => $masterInfo['content']
            );
        }

        // 班牌管理密码
        $ret['brandPassword'] = $brandInfo['brand_password'];
        // 是否启用人脸识别功能
        $ret['brandFaceDetect'] = intval($schoolInfo['school_face_detect']);
        $ret['brandFaceDetectType'] = isset($schoolInfo['school_face_detect_type']) ? intval($schoolInfo['school_face_detect_type']) : intval(FACE_DETECT_TEMPERATURE_TYPE_NORMAL);
        // 是否启用考务功能
        $ret['brandExam'] = intval($schoolInfo['school_exam']);
		// 相机缩放倍数
        $ret['cameraZoom'] = floatval($brandInfo['brand_camera_zoom']);
        // 校训
        $ret['schoolMotto'] = $schoolInfo['school_motto'];

        // 前10条班级通知
        $ret['notifys'] = array();
        if(!empty($notifys)) {
            foreach($notifys as $key => $notify) {
                // 是否置顶
                $notifys[$key]['isTop'] = $notifys[$key]['isTop'] ? true : false;
            }
            $ret['notifys'] = $notifys;
        }
        // 班级通知和校园公告混排
        $topDataArr = array();
        $notTopDataArr = array();
        if(!empty($notifys) || !empty($announces)) {
            foreach($notifys as $notify) {
                $tempArr['cateType'] = 'notify';
                $tempArr['id'] = $notify['id'];
                $tempArr['title'] = $notify['title'];
                $tempArr['time'] = $notify['time'];
                $tempArr['isTop'] = $notify['isTop'] ? true : false;
                $tempArr['contentType'] = $notify['notifyType'];
                $tempArr['externalLink'] = $notify['externalLink'];
                $tempArr['notifyUrgent'] = $notify['notifyUrgent'];
                $tempArr['urgentEndtime'] = $notify['urgentEndtime'];
                if($tempArr['isTop']) {
                    array_push($topDataArr, $tempArr);
                } else {
                    array_push($notTopDataArr, $tempArr);
                }
            }
            foreach($announces as $announce) {
                $tempArr['cateType'] = 'announce';
                $tempArr['id'] = $announce['id'];
                $tempArr['title'] = $announce['title'];
                $tempArr['time'] = $announce['time'];
                $tempArr['isTop'] = $announce['isTop'] ? true : false;
                $tempArr['contentType'] = $announce['announceType'];
                $tempArr['externalLink'] = $announce['externalLink'];
                $tempArr['notifyUrgent'] = '0';
                $tempArr['urgentEndtime'] = '';
                if($tempArr['isTop'] == 1) {
                    array_push($topDataArr, $tempArr);
                } else {
                    array_push($notTopDataArr, $tempArr);
                }
            }
            // 按时间排序
            $timeKey =  array_column($topDataArr, 'time');
            array_multisort($timeKey, SORT_DESC, $topDataArr);
            // 按时间排序
            $timeKey =  array_column($notTopDataArr, 'time');
            array_multisort($timeKey, SORT_DESC, $notTopDataArr);
            // 合并，获取前10项
            $notifyAndAnnounceArr = array_merge($topDataArr, $notTopDataArr);
            if(count($notifyAndAnnounceArr) > 10) {
                $notifyAndAnnounceArr = array_slice($notifyAndAnnounceArr, 0, 10);
            }
            // echo '<pre>';var_export($notifyAndAnnounceArr);exit;
            
            $ret['notifys'] = $notifyAndAnnounceArr;
        }
        // 前10条动态
        $ret['news'] = array();
        if(!empty($news)) {
            $ret['news'] = $news;
        }
        // 是否来自
        $ret['schoolFrom'] = $schoolInfo['school_from'];
        // 对话留言内容发送
        $ret['allowSend'] = $brandInfo['allow_send'];

        // 班牌开关机时间（新逻辑）
        $week = $this->configModel->get_school_campus_config($schoolInfo['id'], $classInfo['campus_id'], 'power_week');
        $holiday = $this->configModel->get_school_campus_config($schoolInfo['id'], $classInfo['campus_id'], 'power_holiday');
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            sort($weekArr);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        // 定时开关机计算好的时间v2
        $brandPowerTimeV2 = $this->_get_power_time_v2($brandInfo['power_time_v2'], $holiday['config_value']);
        if($brandPowerTimeV2['startupTime']){
            // 添加0-5分钟偏移量
            $brandPowerTimeV2['startupTime'] = date("Y-m-d H:i:s", strtotime($brandPowerTimeV2['startupTime']) + rand(0, 5) * 60);
        }
        $ret['brandPowerTime'] = $brandPowerTimeV2;
        // 校训
        $ret['faceSimilar'] = $schoolInfo['face_similar'];

        $ret['smartLock'] = isset($schoolInfo['school_smart_lock']) ? $schoolInfo['school_smart_lock'] : 0;
        // 获取门锁列表
        $smartLockList = array();
        if($ret['smartLock']) {
            $smartLockParams['schoolId'] = $brandInfo['school_id'];
            $smartLockParams['campusId'] = $brandInfo['campus_id'];
            $smartLockParams['classId'] = $brandInfo['class_id'];
            $smartLockParams['isDelete'] = 0;
            $smartLockParams['field'] = 'id, type, token, ip, device_id, device_type';
            $smartLockList = $this->schoolModel->get_smart_lock_list($smartLockParams);
            foreach($smartLockList as $key => $smartLock) {
                // id转换为数字类型
                $smartLockList[$key]['id'] = (int) $smartLock['id'];
                $smartLockList[$key]['type'] = (int) $smartLock['type'];
            }
        }
        $ret['smartLockList'] = $smartLockList;
        // 虹软SDK版本
        $ret['isFreeFaceSdk'] = $schoolInfo['is_free_face_sdk'] ? true : false;

        // 班级主题
        $subjectContent = (object)null;
        $subjectContentTemp = (object)null;
        $subjectContentParams['schoolId'] = $brandInfo['school_id'];
        $subjectContentParams['campusId'] = $brandInfo['campus_id'];
        $subjectContentParams['classId'] = $brandInfo['class_id'];
        // 生效的
        $subjectContentParams['effective'] = 1;
        // 过滤软删除
        $subjectContentParams['isDelete'] = 0;
        $subjectContentParams['field'] = 'type, title, content, videos, play_in_class_mode, endtime, is_full_screen';
        $subjectContentList = $this->contentModel->get_subject_content_list($subjectContentParams);

        if($subjectContentList) {
            $subjectContent = $subjectContentList[0];
            $subjectContentTemp = array();
            $subjectContentTemp['type'] = (int) $subjectContent['type'];
            $subjectContentTemp['title'] = $subjectContent['title'];
            $subjectContentTemp['content'] = $subjectContent['content'];
            $subjectContentTemp['playInClassMode'] = $subjectContent['play_in_class_mode'] ? true : false;
            $subjectContentTemp['endtime'] = $subjectContent['endtime'] . ':59';
            $subjectContentTemp['isFullScreen'] = $subjectContent['is_full_screen'] ? true : false;
            if($subjectContent['type'] == SUBJECT_CONTENT_TYPE_VIDEO && !empty($subjectContent['videos'])) {
                $videos = json_decode($subjectContent['videos'], true);
                foreach($videos as &$video) {
                    unset($video['old_link']);
                }
                $subjectContentTemp['videos'] = $videos;
            } else {
                $subjectContentTemp['videos'] = array();
            }
        }
       
        $ret['subjectContent'] = $subjectContentTemp;

        // 是否启用教师考勤
        $ret['enableTeacherSign'] = $schoolInfo['enable_teacher_sign'] == 1 ? true : false;
        // 班牌类型
        $ret['brandType'] = (int) $brandInfo['type'];
        // 返回服务器时间
        $ret['time'] = date("Y-m-d H:i:s");
        // 是否启用刷卡签到
        $ret['enableCardSign'] = $schoolInfo['enable_card_sign'] == 1 ? true : false;
        // 没课的节次显示走班（排除功能课室和教学班）
        $showTeachingWhenEmpty = false;
        if($schoolInfo['show_teaching_when_empty'] == 1) {
            if($classInfo['class_type'] == CLASSES_TYPE_NORMAL && $classInfo['is_functional'] == 0) {
                $showTeachingWhenEmpty = true;
            }
        }
        $ret['showTeachingWhenEmpty'] = $showTeachingWhenEmpty;
        // 插入版本信息
        if($this->get('version_name') && $brandInfo['version_name'] != $this->get('version_name')) {
            $versionUpdateData = array(
                'version_name' => $this->get('version_name')
            );
            $this->db->update(ClassesModel::$brandTable, $versionUpdateData, array('id' => $brandId));
        }

        // 处理六安大学通知外部链接被退出的问题
        // $autoShowNotifyLink = 'http://ahlalndx.lndxpt3.com/lndx/skipClassRoomCardOther.html?compcode=lalndx&classRoomId=34020017&type=2';
        $autoShowNotifyLink = '';
        if($schoolInfo['school_name'] == '六安市老年大学') {
            // 获取班级通知
            if(isset($notifys[0]) && $notifys[0]['notifyType'] == NOTIFY_TYPE_LINK) {
                $autoShowNotifyLink = $notifys[0]['externalLink'];
            }
            $ret['autoShowNotifyLink'] = $autoShowNotifyLink;
        }
        // $ret['autoShowNotifyLink'] = $autoShowNotifyLink;
        
        exit(json("", true, $ret));
    }
    
    // 获取班牌本周课表接口
    public function get_week_course_data($brandId) {
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
        if($classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        $scheduleArray = $lessonArray = array();
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['campusId'] = $classInfo['campus_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleList = array($mondayGradeSchedule);
            } else {
                $scheduleList = array($scheduleList[0]);
            }
        }
        // var_export($scheduleList);exit;

        if(empty($scheduleList)) {
            exit(json('', true, array()));
        }
        // 只获取本周课表
        $schedule = $scheduleList[0];
        $weekLesson = array();
        $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
        // 判空
        if(!empty($scheduleSetting)){
            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
            // 生成全部课程时间点
            for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {

                // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                if(!$onlyOneSchedule) {
                    // 获取当天的年级作息
                    $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                    if($gradeSchedule) {
                        $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                        $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                    }
                }

                foreach($scheduleSetting as $lessonTime) {
                    $lsData['weekIndex'] = $i;
                    $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                    // // 旧版上课时间
                    // $lsData['startTime'] = $lessonTime['beginTime'];
                    // $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                    // // 新版上课时间
                    // $lsData['startTimeNew'] = $lessonTime['beginTime'] . ':00';
                    // $lsData['endTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                    // if(!isset($lessonTime['sign_interval'])) {
                    //     // 如未设置，默认为10
                    //     $lessonTime['sign_interval'] = 10;
                    // }
                    // // 考勤时间
                    // if($lessonTime['sign_interval'] == 0) {
                    //     $lsData['signStartTime'] = '';
                    //     $lsData['signEndTime'] = '';
                    // } else {
                    //     $lsData['signStartTime'] = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                    //     // 添加0-10秒偏移量
                    //     $lsData['signStartTime'] = date("H:i:s", strtotime($lsData['signStartTime']) + rand(0, 10));

                    //     $lsData['signEndTime'] = date("H:i", strtotime($lessonTime['beginTime']) - 60) . ':59';
                    // }

                    // $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
                    $lsData['lessonName'] = $lsData['teacherName'] = '';
                    $lessonKey = $i. $lsData['classIndex'];

                    // // // 返回sign_interval，供走班情况判断
                    // $lsData['sign_interval'] = $lessonTime['sign_interval'];

                    $weekLesson[$lessonKey] = $lsData;
                }
            }
        }
        // 获取课程表课程
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        // 年级不同作息，不需要传schedule_id
        if($onlyOneSchedule) {
            $lessonParams['scheduleId'] = $schedule['id'];
        }
        $lessonParams['classId'] = $classInfo['id'];
        $lessonParams['classroom'] = $classInfo['classroom_id'];
        $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
                 
        foreach($lessonList as $lesson) {
            $classLesson = $lesson['schedule_lesson'];
            // 写入课程名称
            $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
            $weekLesson[$lessonKey]['id'] = $lesson['id'];
            $weekLesson[$lessonKey]['lessonName'] = $classLesson;
            if(isset($teacherList[$lesson['schedule_teacher']])) {
                // $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                // $weekLesson[$lessonKey]['teacherHeadimg'] = $teacherList[$lesson['schedule_teacher']]['headimgurl']; 
            }
            // 获取班级科目
            if(!in_array($classLesson, $lessonArray)) $lessonArray[] = $classLesson;
        }
        foreach($weekLesson as $key => &$value) {
            // 过滤已删除
            if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                unset($weekLesson[$key]);
                continue;
            }
            if(empty($value['lessonName'])) {
                // 判断是否走班
                $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                // 年级不同作息，不需要传schedule_id
                if(!$onlyOneSchedule) {
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info_for_grade($value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                }

                if($scheduleLesson) {
                    $value['id'] = $scheduleLesson['id'];
                    $value['lessonName'] = '走班';
                    $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
                    // // var_export($value);exit;
                    // // 如进入考勤设置0，走班需固定上课前10分钟进入考勤模式
                    // if(empty($value['signStartTime'])) {
                    //     $value['signStartTime'] = date("H:i", strtotime($value['startTime']) - 10 * 60) . ':00';
                    //     // 添加0-10秒偏移量
                    //     $value['signStartTime'] = date("H:i:s", strtotime($value['signStartTime']) + rand(0, 10));

                    //     $value['signEndTime'] = date("H:i", strtotime($value['startTime']) - 60) . ':59';
                    // }
                }
            }
        }

        $weekLesson = array_values($weekLesson);
        $scheduleArray = $weekLesson;

        // 课程信息
        $ret = $scheduleArray ? $scheduleArray : array();

        exit(json('', true, $ret));
    }

    // 获取班牌当天课表和考试
    public function get_today_course_data($brandId) {
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
        if($classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');

        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['campusId'] = $classInfo['campus_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleList = array($mondayGradeSchedule);
            } else {
                $scheduleList = array($scheduleList[0]);
            }
        }
        // var_export($scheduleList);exit;
        $weekLesson = array();
        if(isset($scheduleList[0])) {
            $schedule = $scheduleList[0];
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 周几
            $scheduleWeekIndex = date('w') != 0 ? date('w') : 7;
            // 判空
            if(!empty($scheduleSetting)){
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {
    
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    if(!$onlyOneSchedule) {
                        // 获取当天的年级作息
                        $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                        if($gradeSchedule) {
                            $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                        }
                    }
    
                    foreach($scheduleSetting as $lessonTime) {
                        // 只获取当天
                        if($i != $scheduleWeekIndex) {
                            continue;
                        }
    
                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        // 旧版上课时间
                        $lsData['startTime'] = $lessonTime['beginTime'];
                        $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                        // 新版上课时间
                        $lsData['startTimeNew'] = $lessonTime['beginTime'] . ':00';
                        $lsData['endTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                        if(!isset($lessonTime['sign_interval'])) {
                            // 如未设置，默认为10
                            $lessonTime['sign_interval'] = 10;
                        }
                        // 考勤时间
                        if($lessonTime['sign_interval'] == 0) {
                            $lsData['signStartTime'] = '';
                            $lsData['signEndTime'] = '';
                        } else {
                            $lsData['signStartTime'] = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                            // 添加0-10秒偏移量
                            $lsData['signStartTime'] = date("H:i:s", strtotime($lsData['signStartTime']) + rand(0, 10));
    
                            $lsData['signEndTime'] = date("H:i", strtotime($lessonTime['beginTime']) - 60) . ':59';
                        }
    
                        $lsData['lessonName'] = $lsData['teacherName'] = '';
                        // $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
    
                        $lessonKey = $i. $lsData['classIndex'];
    
                        // // // 返回sign_interval，供走班情况判断
                        // $lsData['sign_interval'] = $lessonTime['sign_interval'];
    
                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            // 获取课程表课程
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            // 年级不同作息，不需要传schedule_id
            if($onlyOneSchedule) {
                $lessonParams['scheduleId'] = $schedule['id'];
            }
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            // // 只获取当天
            $lessonParams['weekIndex'] =  $scheduleWeekIndex;
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
                        // var_export($weekLesson);exit;
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                if(isset($teacherList[$lesson['schedule_teacher']])) {
                    // $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                    $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                    // $weekLesson[$lessonKey]['teacherHeadimg'] = $teacherList[$lesson['schedule_teacher']]['headimgurl']; 
                }
            }
          
            // 课时数组
            $periodArr = array();
            if($scheduleList[0]) {
                $earlyMorningNum = $scheduleList[0]['schedule_early_morning_number'];
                $nightNum = $scheduleList[0]['schedule_night_number'];
                $lessonNum = $scheduleList[0]['schedule_morning_number'] + $scheduleList[0]['schedule_afternoon_number'];
                for($i = 1; $i <= $earlyMorningNum; $i ++) {
                    $periodArr[] = '';
                }
                for($i = 1; $i <= $lessonNum; $i ++) {
                    $periodArr[] = $i;
                }
                for($i = 1; $i <= $nightNum; $i ++) {
                    $periodArr[] = '';
                }
            }
            // var_export($weekLesson);exit;
            foreach($weekLesson as $key => &$value) {
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    // 年级不同作息，不需要传schedule_id
                    if(!$onlyOneSchedule) {
                        $scheduleLesson = $this->classesModel->get_schedule_lesson_info_for_grade($value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    }
    
                    if($scheduleLesson) {
                        $value['id'] = $scheduleLesson['id'];
                        $value['lessonName'] = '走班';
                        $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
                        // var_export($value);exit;
                        // 如进入考勤设置0，走班需固定上课前10分钟进入考勤模式
                        if(empty($value['signStartTime'])) {
                            $value['signStartTime'] = date("H:i", strtotime($value['startTime']) - 10 * 60) . ':00';
                            // 添加0-10秒偏移量
                            $value['signStartTime'] = date("H:i:s", strtotime($value['signStartTime']) + rand(0, 10));
    
                            $value['signEndTime'] = date("H:i", strtotime($value['startTime']) - 60) . ':59';
                        }
                    }
                }

                // 课时
                if(isset($periodArr[$value['classIndex'] - 1])) {
                    $value['period'] = $periodArr[$value['classIndex'] - 1];
                }
                $value['isExam'] = false;
                unset($value['weekIndex']);

            }          

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
        }

        // var_export($weekLesson);exit;
        $classroomId = $classInfo['classroom_id'];
        // 当天考试开始时间和结束时间
        $examTimeArr = array();
        $todayCourse = array();
        // 获取考场对应的课室
        if($classroomId){
            // 获取学校ID
            $examParams['schoolId'] = $classInfo['school_id'];
            // 获取学校ID
            $examParams['campusId'] = $classInfo['campus_id'];
            // 过滤课室
            $examParams['locationId'] = $classroomId;
            // 获取哪些属性
            $examParams['field'] = 'ed.id, ed.location_id, ed.room_no, ed.room_name, ed.inside_teachers, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.grade_id, er.exam_entry_time_before, er.exam_entry_time_after, er.type, er.exam_id';
            // 根据日期排序
            $examParams['orderBy'] = 'day ASC, begin ASC';
            // 日期参数
            $examParams['day'] = date('Y-m-d');
            $list = $this->dataModel->get_exam_room_detail_list($examParams);
            foreach ($list as $key => $val) {
                // 添加星期几属性
                $list[$key]['week'] = date_to_week($val['day']);
                // 添加科目名
                $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
                $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
                // 获取考试位置
                $classroom = $this->classesModel->get_classroom_info($val['location_id'], 1);
                $list[$key]['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
                // 移除考试位置id
                unset($list[$key]['location_id']);
                // 计算考试时长
                $duration = get_duration($val['begin'], $val['end']);
                $list[$key]['duration'] = $duration;
                // 获取考试年级
                $list[$key]['grade'] = '';
                if(!empty($val['grade_id'])){
                    $grade = $this->classesModel->get_grade_info($val['grade_id']);
                    $list[$key]['grade'] = $grade['grade_name'];
                    unset($list[$key]['grade_id']);
                }
                // 获取场内监考老师
                $list[$key]['inside_teachers'] = [];
                if(isset($val['inside_teachers'])){
                    $idArr = explode(',', $val['inside_teachers']);
                    $nameArr = array();
                    foreach($idArr as $id) {
                        $teacher = $this->schoolModel->get_teacher_info($id);
                        $name = '';
                        if(null !== $teacher){
                            $name = $teacher['realname'];
                        }
                        $nameArr[] = $name;
                    }
                    $list[$key]['inside_teachers'] = $nameArr;
                }
                
                // 转换考试类型为中文
                // 判断是否同时存在等级考和合格考
                $bothHave = false;
                if('chosenExam' === $list[$key]['type']){
                    $queryParams['examId'] = $list[$key]['exam_id'];
                    $queryParams['lessonId'] = $list[$key]['lesson_id'];
                    $queryParams['day'] = $list[$key]['day'];
                    $queryParams['timeslot'] = $list[$key]['timeslot'];
                    $queryParams['type'] = 'studyExam';
                    $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                    if(!empty($queryRes)){
                        $bothHave = true;
                    }
                }
                if('studyExam' === $list[$key]['type']){
                    $queryParams['examId'] = $list[$key]['exam_id'];
                    $queryParams['lessonId'] = $list[$key]['lesson_id'];
                    $queryParams['day'] = $list[$key]['day'];
                    $queryParams['timeslot'] = $list[$key]['timeslot'];
                    $queryParams['type'] = 'chosenExam';
                    $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                    if(!empty($queryRes)){
                        $bothHave = true;
                    }
                }
                $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);
                unset($list[$key]['timeslot']);

                // 计算考勤时间
                $list[$key]['sign_begin_time'] = date('H:i:s', strtotime($val['begin']) - $val['exam_entry_time_before'] * 60);
                $list[$key]['sign_end_time'] = date('H:i:s', strtotime($val['begin']) + $val['exam_entry_time_after'] * 60);

                $list[$key]['isExam'] = true;
            }
            if($list) {
                if($weekLesson) {
                    // 计算当天考试开始时间和结束时间
                    $examTimeArr['beginTime'] = $list[0]['sign_begin_time'];
                    $examTimeArr['endTime'] = $list[count($list) - 1]['end'] . ':00';
           
                    $examInsertIndex = 0;
                    if($examTimeArr) {
                        // 当天存在考试
                        foreach($weekLesson as $value2) {
                            // 兼容签到分钟为0的
                            $lessonBeignTime = $value2['signStartTime'] ? $value2['signStartTime'] : $value2['startTimeNew'];
                            $lessonEndTime = $value2['endTimeNew'];

                            if(($lessonBeignTime < $examTimeArr['beginTime'] && $lessonEndTime <= $examTimeArr['beginTime'])) {
                                $todayCourse[] = $value2;
                            } elseif($lessonBeignTime >= $examTimeArr['endTime'] && $lessonEndTime > $examTimeArr['endTime']) {
                                $todayCourse[] = $value2;
                                if($examInsertIndex == 0) {
                                    $examInsertIndex = $value2['classIndex'];
                                }
                            }
                        }

                        if(empty($todayCourse)) {
                            // 只有考试
                            $todayCourse = $list;
                        } else {
                            // $spliceIndex = count($todayCourse) - 1; // 插入位置，初始值为-1：插入到最后
                            $spliceIndex = - 1; 
                            foreach($todayCourse as $key => $value) {
                                // 获取上课开始时间
                                // 兼容签到分钟为0的
                                $lessonBeignTime = $value['signStartTime'] ? $value['signStartTime'] : $value['startTimeNew'];
                                // 上课开始时间大于考试结束时间
                                if($lessonBeignTime >= $examTimeArr['endTime']) {
                                    // 插入考试的位置
                                    $spliceIndex = $key;
                                    break;
                                }
                            }

                            $tempArr = array();
                            foreach($todayCourse as $key => $value) {
                                if($key == $spliceIndex) {
                                    foreach($list as $examItem) {
                                        $tempArr[] = $examItem; 
                                    }
                                }
                                $tempArr[] = $value;
                            }
                            if($spliceIndex == -1) {
                                // 插入到最后
                                foreach($list as $examItem) {
                                    $tempArr[] = $examItem; 
                                }
                            }
                            // 赋值
                            $todayCourse = $tempArr;
                        }
                    }
                } else {
                    $todayCourse = $list;
                }
            }
        }
        // var_export($weekLesson);exit;
        // 重新获取字段
        $tempArr = $todayCourse ? $todayCourse : $weekLesson;
        $ret = array();
        foreach($tempArr as $tempkey => $tempValue) {
            // 有考试情况，classindex重新排序
            if($examTimeArr) {
                $calssIndex = $tempkey + 1;
            } else {
                $calssIndex = $tempValue['period'];
            }
            if($tempValue['isExam']) {
                $startTime = $tempValue['begin'] . ':00';
                $endTime = $tempValue['end'] . ':00';
                $signStartTime = $tempValue['sign_begin_time'];
                $signEndTime = $tempValue['sign_end_time'];
                $teacherName = $tempValue['inside_teachers'];
                $lessonName = $tempValue['lesson_name'];

                // 如果考试时间短于考试签到时间
                if($signEndTime > $endTime) {
                    $signEndTime = $endTime;
                }
            } else {
                $startTime = $tempValue['startTimeNew'];
                $endTime = $tempValue['endTimeNew'];
                $signStartTime = $tempValue['signStartTime'];
                $signEndTime = $tempValue['signEndTime'];
                $teacherName = $tempValue['teacherName'] ? array($tempValue['teacherName']) : array();
                $lessonName = $tempValue['lessonName'];
            }

            $ret[] = array(
                "id"=> isset($tempValue['id']) ? $tempValue['id'] : '',
                "classIndex"=> (string) $calssIndex,
                "startTime"=> $startTime,
                "endTime"=> $endTime,
                "signStartTime"=> $signStartTime,
                "signEndTime"=> $signEndTime,
                "lessonName"=> $lessonName,
                "teacherName"=> $teacherName,
                "isExam"=> $tempValue['isExam']
            );
        }
        exit(json('', true, $ret));
    }

    // 获取班牌今天所有的人脸数据
    public function get_brand_face_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
            // 兼容身份证
            $stuParams['classORteach'] = $classInfo['id'];
            // $stuParams['schoolId'] = $brandInfo['school_id'];
            $stuParams['isDelete'] = 0;
        } else {
            // 获取校区ID
            $campusId = $classInfo['campus_id'];
            // 获取课室id
            $classroomId = $classInfo['classroom_id'];

            // 获取本周课程作息
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
            if($onlyOneSchedule) {
                $scheduleInfo = $this->classesModel->get_campus_schedule($campusId);
            } else {
                // 转换date('w')获取的值为作息时间的week
                $this->load->helper('schedule');
                $week = transform__to_schedule_week(date('w'));
                // 获取当天的年级作息
                $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $week);
                if($gradeSchedule) {
                    $scheduleInfo = $gradeSchedule;
                }
            }

            // 获取本周所有课程
            $weekIndex = date("w",time());
            $params['weekIndex'] = $weekIndex ? $weekIndex : 7;
            if($scheduleInfo) {
                $params['scheduleId'] = $scheduleInfo['id'];
            }
            $params['classroom'] = $classroomId;
            $lessonList = $this->classesModel->get_school_schedule_lesson($params);
            // 获取所有班级，包含本班，避免无课表的情况
            $classArray = array(
                $classInfo['id']
            );
            foreach ($lessonList as $lesson) {
                if(!in_array($lesson['class_id'], $classArray)) {
                    $classArray[] = $lesson['class_id'];
                }
            }
            //  获取班级所有学生
                        // 兼容身份证
            $stuParams['classORteach'] = implode(",", $classArray);
            // $stuParams['schoolId'] = $brandInfo['school_id'];
            $stuParams['isDelete'] = 0;
        }

        $studentList = $this->schoolModel->get_student_list($stuParams);
        // 返回值
        $ret = array();
        foreach($studentList as $student) {
            $data['id'] = $student['id'];
            $data['userType'] = USER_TYPE_STUDENT;
            $data['name'] = $student['realname'];
            $data['faceImage'] = $student['face_image'];
            $data['cardNum'] = $student['realcard'];
            $ret[] = $data;
        }

        // 获取任课教师列表
        $coachParams['schoolId'] = $brandInfo['school_id'];
        $coachParams['campusId'] = $brandInfo['campus_id'];
        $coachParams['classId'] = $brandInfo['class_id'];
        $coachParams['isDelete'] = 0;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $coachTeacherIdArr = array();
        foreach($coachList as $coach) {
            if(!in_array($coach['teacher_id'], $coachTeacherIdArr)) {
                array_push($coachTeacherIdArr, $coach['teacher_id']);
            }
        }
        // 获取当天上课老师

         // 获取本校全部老师
        $teacherParams['schoolId'] = $classInfo['school_id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['campusId'] = $classInfo['campus_id'];
        // 只取本周的
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleList = array($mondayGradeSchedule);
            } else {
                $scheduleList = array($scheduleList[0]);
            }
        }
        $weekLesson = array();
        if(isset($scheduleList[0])) {
            $schedule = $scheduleList[0];
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 周几
            $scheduleWeekIndex = date('w') != 0 ? date('w') : 7;
            // 判空
            if(!empty($scheduleSetting)){
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    if(!$onlyOneSchedule) {
                        // 获取当天的年级作息
                        $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                        if($gradeSchedule) {
                            $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                        }
                    }
                    foreach($scheduleSetting as $lessonTime) {
                        // 只获取当天
                        if($i != $scheduleWeekIndex) {
                            continue;
                        }
    
                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        $lsData['lessonName'] = $lsData['teacherId'] = '';
                        // $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
    
                        $lessonKey = $i. $lsData['classIndex'];
                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            // 获取课程表课程
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            // 年级不同作息，不需要传schedule_id
            if($onlyOneSchedule) {
                $lessonParams['scheduleId'] = $schedule['id'];
            }
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            // // 只获取当天
            $lessonParams['weekIndex'] =  $scheduleWeekIndex;
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                if(isset($teacherList[$lesson['schedule_teacher']])) {
                    $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                }
            }
            foreach($weekLesson as $key => &$value) {
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    // 年级不同作息，不需要传schedule_id
                    if(!$onlyOneSchedule) {
                        $scheduleLesson = $this->classesModel->get_schedule_lesson_info_for_grade($value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    }

                    if($scheduleLesson) {
                        $value['id'] = $scheduleLesson['id'];
                        $value['lessonName'] = '走班';
                        $value['teacherId'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['id'] : '';
                    }
                }
            }
        }
        foreach($weekLesson as $item) {
            if($item['teacherId'] && !in_array($item['teacherId'], $coachTeacherIdArr)) {
                array_push($coachTeacherIdArr, $item['teacherId']);
            }
        }
        foreach($coachTeacherIdArr as $coachTeacherId) {
            if(isset($teacherList[$coachTeacherId])) {
                $data['id'] = $coachTeacherId;
                $data['userType'] = USER_TYPE_TEACHER;
                $data['name'] = $teacherList[$coachTeacherId]['realname'];
                $data['faceImage'] = $teacherList[$coachTeacherId]['face_image'];
                $data['cardNum'] = '';
                $ret[] = $data;
            }
        }

        exit(json("", true, $ret));
    }

    // 更新人脸
    public function update_face_image($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty(trim($this->post("user_type"))) || empty(trim($this->post("user_id")))) {
            throw new Exception('参数错误');
        }
        $userType = trim($this->post("user_type"));
        $userId = trim($this->post("user_id")); 
        // 用户类型
        if($userType == USER_TYPE_TEACHER) {
            // 教师
            $userInfo = $this->schoolModel->get_teacher_info($userId);
        } else if($userType == USER_TYPE_STUDENT) {
            // 默认是学生
            $userInfo = $this->schoolModel->get_student_info($userId);
        } else {
            throw new Exception('参数错误');
        }
        if(empty($userInfo)) {
            throw new Exception('用户不存在');
        }
        if($userInfo['school_id'] != $brandInfo['school_id']) {
            throw new Exception('用户不存在');
        }
        if($this->post("face_image_url")) {
            $webUrl = $this->post("face_image_url");
        } else {
            // 获取图片base64值
            $imageBase64 = $this->post("face_image", false);
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("更新失败，图片参数错误");


            $this->load->library('localuploader');
            $webUrl = $this->localuploader->uploadBase64Image($imageBase64);
            if($webUrl == false) {
                throw new Exception('系统错误，请联系管理员');
            }
        }

        $update['face_image'] = $webUrl;
        if($userType == USER_TYPE_TEACHER) {
            $this->db->update(SchoolModel::$schoolUserTable, $update, "id='{$userInfo['id']}'");
        } else if($userType == USER_TYPE_STUDENT) {
            $this->db->update(SchoolModel::$schoolStudentTable, $update, "id='{$userInfo['id']}'");
        }

        // 插入闸机任务
        $gateParams['schoolId'] = $brandInfo['school_id'];
        $gateParams['campusId'] = $brandInfo['campus_id'];
        // 过滤软删除
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            if($userInfo['face_image']) {
                // 更新
                $taskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $taskType = GATE_TASK_TYPE_ADD;
            }
            $insertTaskBatch = array();
            foreach($gateList as $gate) {
                array_push($insertTaskBatch, array(
                    'school_id' => $brandInfo['school_id'],
                    'campus_id' => $brandInfo['campus_id'],
                    'gate_id' => $gate['id'],
                    'device_sn' => $gate['device_sn'],
                    'user_id' => $userInfo['id'],
                    'user_name' => $userInfo['realname'],
                    'user_face_image' => $update['face_image'],
                    'user_type' => $userType == USER_TYPE_TEACHER ? GATE_USER_TYPE_TEACHER : GATE_USER_TYPE_STUDENT,
                    'task_type' => $taskType,
                    'task_state' => GATE_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
            }
        }

        // 插入一体机任务
        $this->load->model('aioModel');
        $aioParams['schoolId'] = $brandInfo['school_id'];
        $aioParams['campusId'] = $brandInfo['campus_id'];
        // 过滤软删除
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            if($userInfo['face_image']) {
                // 更新
                $taskType = AIO_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $taskType = AIO_TASK_TYPE_ADD;
            }
            $insertTaskBatch = array();
            foreach($aioList as $aio) {
                array_push($insertTaskBatch, array(
                    'school_id' => $brandInfo['school_id'],
                    'campus_id' => $brandInfo['campus_id'],
                    'aio_id' => $aio['id'],
                    'facesluice_id' => $aio['facesluice_id'],
                    'user_id' => $userInfo['id'],
                    'user_name' => $userInfo['realname'],
                    'user_face_image' => $update['face_image'],
                    'user_type' => $userType == USER_TYPE_TEACHER ? AIO_USER_TYPE_TEACHER : AIO_USER_TYPE_STUDENT,
                    'task_type' => $taskType,
                    'task_state' => AIO_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
            }
        }

        // 返回成功提示和头像地址
        exit(json("人脸上传成功", true,  $update['face_image']));
    }

    // 学生课程签到接口（版本2）
    public function sign($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('staffModel');
        $this->load->model('dataModel');
        // 用户类型
        $userType = trim($this->post("user_type"));
        if(empty($userType)) {
            throw new Exception('用户类型参数不能为空');
        }
        // 签到类型
        $signType = $this->post("sign_type") ? $this->post("sign_type") : SIGN_TYPE_CARD;
        // 签到图片，base64与url二选一
        $imageBase64 = $this->post("sign_image", false);
        $imageUrl = $this->post("sign_image_url");
        if(empty($imageBase64) && empty($imageUrl)) {
            throw new Exception('图片参数不能为空');
        }
        if($imageBase64 && $imageUrl) {
            throw new Exception('图片参数错误');
        }
        if($imageBase64) {
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("签到失败，图片参数错误");
        }

        // 签到时间
        $signTime = $this->post("sign_time");
        if(!$signTime) throw new Exception("签到失败，签到时间不能为空");
        // 是否离校
        $isLeave = $this->post("is_leave") ? $this->post("is_leave") : 0;
        // 是否补签
        $isSupplement = $this->post('is_supplement') ? $this->post('is_supplement') : 0;

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        // 如果有传课程ID，则根据当前课程获取班级信息
        $isTeachingSign = false; // 是否走班
        $isElectiveSign = false;
        $courseId = $this->post("course_id") ? $this->post("course_id") : 0;
        if(!$courseId) throw new Exception("签到失败，课程id参数错误");
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
            if($courseInfo['class_id'] != $brandInfo['class_id']) {
                $isTeachingSign = true;
                // 判断是否为选修班
                if($classInfo['class_type'] == CLASSES_TYPE_ELECTIVE) {
                    $isElectiveSign = true;
                }
            }
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("签到失败，获取不到当前课程班级信息");
        // 判断温度
        if($signType == SIGN_TYPE_TEMPERATURE || $signType == SIGN_TYPE_TEMPERATURE_HEAD || $signType == SIGN_TYPE_TEMPERATURE_WRIST) {
            if(empty($this->post('temperature'))) {
                throw new Exception("缺少温度参数");
            }
        }
        
        // 传卡号优先判断卡号
        if($this->post("cardnum")) {
            $realcard = $this->post("cardnum");
            // 通过卡号获取学生
            $userInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            $userType = USER_TYPE_STUDENT;
            if(empty($userInfo)) {
                // 通过卡号获取老师
                $userInfo = $this->schoolModel->get_teacher_info_by_realcard($realcard, $brandInfo['school_id']);
                $userType = USER_TYPE_TEACHER;
            }
            // // 通过身份证获取学生
            // if(empty($userInfo)) {
            //     // 通过身份证获取学生
            //     $userInfo = $this->schoolModel->get_student_info_by_shenfenzheng($realcard, $brandInfo['school_id']);
            //     $userType = USER_TYPE_STUDENT;
            // }
            if(empty($userInfo)) {
                throw new Exception("卡号不存在");
            }
        } else {
            if($userType == USER_TYPE_STUDENT) {
                // 获取学生信息
                if(empty($this->post('user_id'))) {
                    throw new Exception("签到失败，用户id参数错误");
                }
                $userInfo = $this->schoolModel->get_student_info($this->post('user_id'));
            } else {
                // 获取教师信息
                if(empty($this->post('user_id'))) {
                    throw new Exception("签到失败，用户id参数错误");
                }
                $userInfo = $this->schoolModel->get_teacher_info($this->post('user_id'));
            }
        }
        if(!$userInfo) throw new Exception("签到失败，用户不存在");


        // 兼容身份证
        // if($userType == USER_TYPE_STUDENT) {
        //     // 获取兴趣班id
        //     $teachClassArray = explode(",", $userInfo['teaching_class_id']);
        //     $electiveClassArray = explode(",", $userInfo['elective_class_id']);
        //     if($userInfo['class_id'] != $classInfo['id'] && !in_array($classInfo['id'], $teachClassArray) && !in_array($classInfo['id'], $electiveClassArray)) {
        //         // throw new Exception("签到失败，该名学生不在本班级上课");
        //         exit(json('签到失败，该名学生不在本班级上课', true));
        //     }
        // } else {
        //     if($userInfo['school_id'] != $classInfo['school_id']) {
        //         exit(json('签到失败，该用户不是本校教师', true));
        //     }
        // }

        // 判断10分钟内是否有重复提交
        $signInfo = $this->classesModel->get_sign_info_by_createtime(date("Y-m-d H:i:s", strtotime($signTime)), $userInfo['id'], $courseId, $userType);
        if($signInfo) {
            // 测试服不限制
            if(ENV != 'test' && ENV != 'local') {
                // throw new Exception('10分钟内不需要重复签到');
                exit(json('10分钟内不需要重复签到', true));
            }
        }

        if($imageBase64) {

            $this->load->library('localuploader');
            $signImg = $this->localuploader->uploadBase64Image($imageBase64);
            if($signImg == false) {
                throw new Exception('系统错误，请联系管理员');
            }
        } else {
            // 图片url
            $signImg = $imageUrl;
        }
        if($this->post('temperature')) {
            $temperature = $this->post('temperature');
            if(!is_numeric($temperature)) {
                throw new Exception("温度格式错误");
            }
            // 限制为1位小数
            $temperature = sprintf("%.1f", $temperature);
        } else {
            $temperature = '';
        }
        // 处理签到状态
        if($isLeave) {
            $state = SIGN_STATE_LEAVE;
        } else {
            // 判断是否补签
            if($isTeachingSign) {
                if($isElectiveSign) {
                    // 选修班
                    if($isSupplement) {
                        $state = SIGN_STATE_ELECTIVE_SUPPLEMENT;
                    } else {
                        $state = SIGN_STATE_ELECTIVE;
                    }
                } else {
                    // 走班
                    if($isSupplement) {
                        $state = SIGN_STATE_TEACH_SUPPLEMENT;
                    } else {
                        $state = SIGN_STATE_TEACH;
                    }
                }
            } else {
                // 行政班
                if($isSupplement) {
                    $state = SIGN_STATE_NORMAL_SUPPLEMENT;
                } else {
                    $state = SIGN_STATE_NORMAL;
                }
            }
        }

        // 判断是否‘重新签到’的签到
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $brandInfo['school_id'];
        $schduleParams['campusId'] = $brandInfo['campus_id'];
        $schduleParams['isThisWeek'] = 1;
        // 兼容不同年级作息
        $schduleParams['gradeId'] = $classInfo['grade_id'];
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        $classIndex = 1;
        $time = date("H:i:s", strtotime($signTime));
        foreach($timeArr as $lessonKey => $lessonTime) {  
            // 如未设置，默认为10
            if(!isset($lessonTime['sign_interval'])) {
                $lessonTime['sign_interval'] = 10;
            }
            // 课程结束时间
            $signStartTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
            // 小于第一节情况
            if($lessonKey == 0) {
                if($time <= $signStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
            // 大于最后一节情况
            if($lessonKey == count($timeArr) - 1) {
                if($time >= $signStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
            // 其他情况
            if($lessonKey < count($timeArr) - 1) {
                if(!isset($timeArr[$lessonKey + 1]['sign_interval'])) {
                    $timeArr[$lessonKey + 1]['sign_interval'] = 10;
                }
                // 下节课考勤开始时间
                $nextSignStartTime = date("H:i", strtotime($timeArr[$lessonKey + 1]['beginTime']) - ($timeArr[$lessonKey + 1]['sign_interval']) * 60) . ':00';
                // 大于等于当前考勤开始时间，小于下节考勤开始时间
                if($time >= $signStartTime && $time < $nextSignStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
        }
        $refreshClassIndex = 0;
        foreach($timeArr as $key => $time) {
            if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
                $refreshClassIndex = $key + 1;
            }
        }
        $date = date("Y-m-d", strtotime($signTime));
        // 获取学生当天最后一次签到
        $signData = $this->dataModel->get_student_sign_data($date, $userInfo['id'], '', $userType);

        if($signData['sign_id'] && $signData['schedule_class_index'] >= $refreshClassIndex) {
            // 不是‘重新签到’
            $refreshSign = false;
        } else {
            // 是‘重新签到’
            $refreshSign = true;
        }

        $insert['sign_is_submit'] = 0;
        // 教师签到不需要
        if($userType == USER_TYPE_STUDENT) {
            // 如果是同步学校，设置sign_is_submit=1
            $schoolInfo = $this->schoolModel->get_school_info($userInfo['school_id']);
            if($schoolInfo['school_from'] == X_DATA_HAOZHUANYE) {
                $insert['sign_is_submit'] = 1;
            } else {
                $insert['sign_is_submit'] = 0;
            }
        }

        // 入库，做个毛线逻辑
        $insert['school_id'] = $classInfo['school_id'];
        $insert['class_id'] = $classInfo['id'];
        $insert['course_id'] = $courseId;
        $insert['student_id'] = $userInfo['id'];
        $insert['student_card_number'] = $userType == USER_TYPE_STUDENT ? $userInfo['realcard'] : '';
        $insert['brand_id'] = $brandInfo['id'];
        $insert['sign_type'] = $signType;
        $insert['state'] = $state;
        $insert['sign_img'] = $signImg;
        $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
        $insert['temperature'] = $temperature;
        $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
        $insert['user_type'] = $userType;
        $this->db->insert(ClassesModel::$signTable, $insert);

        // 返回值
        $ret['name'] = $userInfo['realname'];
        $ret['signId'] = $this->db->insert_id();

        // 插入考勤临时表
        $this->db->insert(ClassesModel::$signTempTable, $insert);
        exit(json("", true, $ret));
    }

    // 获取教师风采(教师列表)
    public function get_class_teacher_list($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('staffModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));

        // 获取本校全部老师
        $teacherParams['schoolId'] = $classInfo['school_id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');

        // 获取全校科目列表
        $subjectParams['schoolId'] = $classInfo['school_id'];
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'id');

        // 获取任课教师列表
        $coachParams['schoolId'] = $brandInfo['school_id'];
        $coachParams['campusId'] = $brandInfo['campus_id'];
        $coachParams['classId'] = $brandInfo['class_id'];
        $coachParams['coachType'] = COACH_TYPE_TEACHER;
        $coachParams['isDelete'] = 0;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $coachTeacherIdArr = array();
        $ret = array();
        $teacherAndSubjectArr = array();
        foreach($coachList as $coach) {
            if($coach['subject_ids']) {
                $subjectId = explode(',', $coach['subject_ids'])[0];
                if(isset($subjectList[$subjectId])) {
                    // 获取执教科目
                    $subjectName = $subjectList[$subjectId]['lesson_name'];
                    $teacherAndSubjectArr[$coach['teacher_id']] = $subjectName;
                }
            }

            if(!in_array($coach['teacher_id'], $coachTeacherIdArr)) {
                array_push($coachTeacherIdArr, $coach['teacher_id']);
            }
        }

        foreach($coachTeacherIdArr as $coachTeacherId) {
            if(isset($teacherList[$coachTeacherId])) {
                $data['id'] = $coachTeacherId;
                $data['name'] = $teacherList[$coachTeacherId]['realname'];
                $data['headimgurl'] = $teacherList[$coachTeacherId]['headimgurl'];
                $data['faceImage'] = $teacherList[$coachTeacherId]['face_image'];
                $data['desc'] = urlencode($teacherList[$coachTeacherId]['content']);
                if(isset($teacherAndSubjectArr[$coachTeacherId])) {
                    $data['lesson'] = $teacherAndSubjectArr[$coachTeacherId];
                }
                $ret[] = $data;
            }
        }
        exit(json("", true, $ret));
    }

    // 检查当前课程信息
    public function get_current_course($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        if(!$classInfo['classroom_id']) exit(json("不存在的教室ID", false));

        // 获取本周课程
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if($onlyOneSchedule) {
            $schedule = $this->classesModel->get_campus_schedule($classInfo['campus_id']);
        } else {
            // 转换date('w')获取的值为作息时间的week
            $this->load->helper('schedule');
            $week = transform__to_schedule_week(date('w'));
            // 获取当天的年级作息
            $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $week);
            if($gradeSchedule) {
                $schedule = $gradeSchedule;
            }
        }
        if(empty($schedule)) {
            exit(json("没有对应作息时间"));
        }
    
        $timeJson = json_decode($schedule['schedule_time_json'], true);

        // 获取当前时间
        $currentTime = $this->post('time') ? $this->post('time') : date("H:i:s");
        // 当前课程节数
        $courseIndex = 0;
        $courseStartTime = $courseEndTime = $signStartTimeNew = $signEndTimeNew = "";
        // 判断timejson是否为NULL
        if(null !== $timeJson){
            // 获取当前时间是第几节课
            foreach($timeJson as $timePoint) {
                // 如为设置，默认为10
                if(!isset($timePoint['sign_interval'])) {
                    $timePoint['sign_interval'] = 10;
                }
                // interval如为0，走班也设置为10
                // 新版上课时间
                $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - ($timePoint['sign_interval']) * 60) . ':00';
                $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                    $courseIndex = $timePoint['timeslotInDay'];
                    $courseStartTime = $timePoint['beginTime'];
                    $courseEndTime = $classEnd;
                    if($timePoint['sign_interval'] == 0) {
                        $signStartTimeNew = '';
                        $signEndTimeNew = '';
                    } else {
                        $signStartTimeNew = $signStartNew;
                        $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                    }
                    break;
                }
            }
            // 处理走班interval设置为0的情况
            if($courseIndex == 0) {
                foreach($timeJson as $timePoint) {
                    // 如为设置，默认为10
                    if(!isset($timePoint['sign_interval'])) {
                        $timePoint['sign_interval'] = 10;
                    }
                    if($timePoint['sign_interval'] == 0) {
                        // 新版上课时间
                        $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                        $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - 10 * 60) . ':00';
                        $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                        if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                            $courseIndex = $timePoint['timeslotInDay'];
                            $courseStartTime = $timePoint['beginTime'];
                            $courseEndTime = $classEnd;
                            if($timePoint['sign_interval'] == 0) {
                                $signStartTimeNew = '';
                                $signEndTimeNew = '';
                            } else {
                                $signStartTimeNew = $signStartNew;
                                $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            exit(json("没有对应课程"));
        }
        
        // var_export($signStartNew);exit;
        // 获取本周指定课程信息
        $weekIndex = date("w",time());
        $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7

        // // 河西学校返回周五课程
        // if($brandInfo['school_id'] == 32) {
        //     $weekIndex = 5;
        // }

        // 获取本次上课信息
        $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);
        if($timePoint['sign_interval'] == 0 && $scheduleLesson['class_id'] != $classInfo['id']) {
            $signStartTimeNew = date("H:i", strtotime($courseStartTime) - 10 * 60) . ':00';
            $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
        }
        if(!$courseIndex || !$scheduleLesson) exit(json("没有对应课程"));

        // 是否走班课
        if($scheduleLesson['class_id'] != $classInfo['id']) {
            // 走班课
            $isTeachingLesson = true;
        } else {
            // 不是走班课
            $isTeachingLesson = false;
        }
        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info($scheduleLesson['schedule_teacher']);
        // 支持多个授课老师
        $scheduleTeacherIdArr = explode(',', $scheduleLesson['schedule_teacher']);
        $teacherInfoArr = array();
        // 支持多个授课老师
        $teacherArrTemp = array();
        // 老师考勤数据
        $teahcerSignArrTemp = array();
        foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
            $teacherInfo = $this->schoolModel->get_teacher_info($scheduleTeacherId);
            if($teacherInfo) {
                array_push($teacherInfoArr, $teacherInfo);

                // 获取教师考勤
                $teacherSignParams['schoolId'] = $teacherInfo['school_id'];
                $teacherSignParams['teacherId'] = $teacherInfo['id'];
                $teacherSignParams['courseId'] = $scheduleLesson['id'];
                $teacherSignParams['signDate'] = date("Y-m-d");
                $teacherSignList = $this->dataModel->get_teacher_sign_data($teacherSignParams);
                $teahcerSignArrTemp[$teacherInfo['id']] = $teacherSignList;
                if($teacherSignList) {
                    $hasSign = true;
                } else {
                    $hasSign = false;
                }
                array_push($teacherArrTemp, array(
                    'id' => $teacherInfo['id'],
                    'teacherName' => $teacherInfo['realname'],
                    'teacherHeadimgurl' => $teacherInfo['headimgurl'],
                    'hasSign' => $hasSign
                ));
            }
        }
        $ret['teacherList'] = $teacherArrTemp;

        // 获取当前班级信息
        $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
        // 返回课程信息
        $ret['courseId'] = $scheduleLesson['id'];
        $ret['startTime'] = $courseStartTime;
        $ret['endTime'] = $courseEndTime;
        // 新版上课时间
        $ret['startTimeNew'] = $courseStartTime . ':00';
        $ret['endTimeNew'] = date("H:i", strtotime($courseEndTime) - 60) . ':59';
        $ret['signStartTimeNew'] = $signStartTimeNew;
        $ret['signEndTimeNew'] = $signEndTimeNew;

        $ret['className'] = $courseClassInfo['class_name'] ? $courseClassInfo['class_name'] : '';
        $ret['lessonName'] = $scheduleLesson['schedule_lesson'];
        $ret['teacherName'] = $teacherInfo['realname'] ? $teacherInfo['realname'] : '';
        $ret['teacherHeadimgurl'] = $teacherInfo['headimgurl'] ? $teacherInfo['headimgurl'] : '';

        // 获取科目
        $lessonInfo = $this->schoolModel->get_lesson_info_by_name($scheduleLesson['schedule_lesson'], $brandInfo['school_id']);
        // 课程模式和课程图片
        $lessonMode = '上课模式';
        $lessonImg = 'https://resource.rongmixiao.com/default/classTime.png';
        if($lessonInfo) {
            if(trim($lessonInfo['lesson_mode'])) {
                $lessonMode = trim($lessonInfo['lesson_mode']);
            }
            if(trim($lessonInfo['lesson_img'])) {
                $lessonImg = trim($lessonInfo['lesson_img']);
            }
        }
        $ret['lessonMode'] = $lessonMode;
        $ret['lessonImg'] = $lessonImg;

        // 是否返回本节课学生考勤情况，默认不返回
        if($this->post('sign_data')) {
            // 获取之前最近的重新签到课程，包含本节课
            $schduleParams['schoolId'] = $brandInfo['school_id'];
            $schduleParams['campusId'] = $brandInfo['campus_id'];
            $schduleParams['isThisWeek'] = 1;
            // 兼容不同年级作息
            $schduleParams['gradeId'] = $classInfo['grade_id'];
            $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
            $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
            $classIndex = $courseIndex;
            $refreshClassIndex = 0;
            foreach($timeArr as $key => $time) {
                if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
                    $refreshClassIndex = $key + 1;
                }
            }
            // 获取学生考勤信息
            $today = date("Y-m-d");
            $isTeachingClass = $scheduleLesson['class_id'] != $brandInfo['class_id'];
            $studentList = $this->dataModel->get_sign_data_fast_by_classindex($courseClassInfo, $today, $isTeachingClass, $scheduleLesson['id'], '', $brandInfo['school_id'], $scheduleLesson['schedule_class_index']);
            
            // echo '<pre>';var_export($studentList);exit;
            // 检查用户签到情况
            $signArray = array(
                "sign" => array(
                    'count' => 0,
                    'data' => array()
                ),
                "noSign" => array(
                    'count' => 0,
                    'data' => array()
                )
            );

            // echo '<pre>';var_export($studentList);exit;
            // 临时课程数据
            $tempCourseArr = array();
            foreach($studentList as $student) {
                $studentData = array(
                    "id" => $student['sign_id'],
                    "studentId" => $student['id'],
                    "studentCard" => $student['realcard'],
                    "name" => $student['realname'],
                    "image" => $student['sign_img']. "!small",
                    "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                    "signTimeDetail" => $student['signTime'] ? $student['signTime'] : '',
                    "faceImage" => $student['face_image'],
                    "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                    "temperature" => $student['temperature'] ? $student['temperature'] : ''
                );

                // 判断离校
                if($student['sign_id'] && $student['state'] != SIGN_STATE_LEAVE) {
                    // 查询临时数组是否有class_index数据
                    // 如果有则读取临时数组
                    // 如果没有，则查询数据库。将查询数据保存到临时数组
                    $scheduleClassIndex = 0;
                    if($student['course_id']) {
                        if(isset($tempCourseArr[$student['course_id']])) {
                            $scheduleClassIndex = $tempCourseArr[$student['course_id']];
                        } else {
                            $courseInfo = $this->dataModel->get_school_schedule_lesson($student['course_id']);
                        }
                        if($courseInfo) {
                            $scheduleClassIndex = $courseInfo['schedule_class_index'];
                            $tempCourseArr[$courseInfo['id']] = $scheduleClassIndex;
                        }
                    }

                    // 判断签到是否在‘最近重新签到’后
                    if($scheduleClassIndex && $scheduleClassIndex >= $refreshClassIndex) {
                        $signArray['sign']['data'][] = $studentData;
                    } else {
                        $studentData['id'] = '';
                        $studentData['image'] = '';
                        $signArray['noSign']['data'][] = $studentData;
                    }
                } else {
                    $studentData['id'] = '';
                    $studentData['image'] = '';
                    $signArray['noSign']['data'][] = $studentData;
                }
            }
            // echo '<pre>';var_export($tempCourseArr);exit;
            $signArray['sign']['count'] = count($signArray['sign']['data']);
            $signArray['noSign']['count'] = count($signArray['noSign']['data']);
            $ret['studentSignData'] = $signArray;

            // 教师考勤数据
            // 检查用户签到情况
            $teacherSignArray = array(
                "sign" => array(
                    'count' => 0,
                    'data' => array()
                ),
                "noSign" => array(
                    'count' => 0,
                    'data' => array()
                )
            );
            // 支持多个授课老师
            if($teacherInfoArr) {
                $signArr = array();
                $notSignArr = array();
                foreach($teacherInfoArr as $teacherInfo) {
                    // 获取教师考勤
                    $teacherSignList = isset($teahcerSignArrTemp[$teacherInfo['id']]) ? $teahcerSignArrTemp[$teacherInfo['id']] : array();
                    // exit(json("", true, $teacherSignList));
                    $tempData = array(
                        'id' => '',
                        'teacherId' => $teacherInfo['id'],
                        'name' => $teacherInfo['realname'],
                        'image' => '',
                        'signTime' => '',
                        'signTimeDetail' => '',
                        'faceImage' => $teacherInfo['face_image'],
                        'headimgurl' => $teacherInfo['headimgurl'],
                        'temperature' => ''
                    );
                    if($teacherSignList) {
                        $teacherSign = $teacherSignList[0];
                        $tempData['id'] = $teacherSign['id'];
                        $tempData['image'] = $teacherSign['sign_img'] . "!small";
                        $tempData['signTime'] = $teacherSign['createtime'] ? date("H时i分", strtotime($teacherSign['createtime'])) : '';
                        $tempData['signTimeDetail'] = $teacherSign['createtime'];
                        $tempData['temperature'] = $teacherSign['temperature'];
                        array_push($signArr, $tempData);
                    } else {
                        array_push($notSignArr, $tempData);
                    }
                }
                  
                $teacherSignArray['sign'] = array(
                    'count' => count($signArr),
                    'data' => $signArr
                );
                $teacherSignArray['noSign'] = array(
                    'count' => count($notSignArr),
                    'data' => $notSignArr
                );
            }
            $ret['teacherSignData'] = $teacherSignArray;
        }

        // 返回‘上午考勤’
        $singTitle = '';
        if($isTeachingLesson) {
            $singTitle = '走班考勤';
        } else {
            $h = explode(':', $currentTime)[0];
            if($h >= 18) {
                $singTitle = '晚上考勤';
            } else if($h >= 12) {
                $singTitle = '下午考勤';
            } else {
                $singTitle = '上午考勤';
            }
        }
        $ret['signTitle'] = $singTitle;

        // // 插入教师考勤记录
        // foreach($ret['teacherList'] as $teacher) {
        //     // 判断是否有记录
        //     $teacherSignRecordParams['schoolId'] = $brandInfo['school_id'];
        //     $teacherSignRecordParams['teacherId'] = $teacher['id'];
        //     $teacherSignRecordParams['signDate'] = date('Y-m-d');
        //     $teacherSignRecordParams['scheduleClassIndex'] = $courseIndex;
        //     $teacherSignRecordInfo = $this->dataModel->get_teacher_sign_record_info($teacherSignRecordParams);
        //     if(empty($teacherSignRecordInfo)) {
        //         // 获取课程班级信息
        //         $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
        //         $teacherSignRecordData = array(
        //             'school_id' => $brandInfo['school_id'],
        //             'grade_id' => $courseClassInfo['grade_id'],
        //             'course_id' => $scheduleLesson['id'],
        //             'course_class_id' => $scheduleLesson['class_id'],
        //             'subject_name' => $scheduleLesson['schedule_lesson'],
        //             'teacher_id' => $teacher['id'],
        //             'brand_id' => $brandId,
        //             'brand_class_id' => $brandInfo['class_id'],
        //             'schedule_week_index' => $weekIndex,
        //             'schedule_class_index' => $courseIndex,
        //             'sign_date' => date('Y-m-d'),
        //             'createtime' => date('Y-m-d H:i:s')
        //         );
        //         // 插入记录
        //         $this->db->insert(DataModel::$teacherSignRecordTable, $teacherSignRecordData);
        //     }
        // }

        // 二维码签到
        if($brandInfo['school_id'] == 54 || $brandInfo['school_id'] == 55 || $brandInfo['school_id'] == 29) {
            // 判断是否需要签到
            $nowtime = date('H:i:s');
            // $nowtime = '18:30:00';
            if($nowtime >= $ret['signStartTimeNew'] && $nowtime <= $ret['signEndTimeNew']) {
                $isSupplement = 0;
            } else {
                // 补签
                $isSupplement = 1;
            }
            $queryParams = array(
                // 'course_id' => $ret['courseId'],
                'brand_id' => $brandId,
                // 'is_supplement' => $isSupplement
            );
            $queryStr = http_build_query($queryParams);
            $ret['qrcodeUrl'] = admin_url('brand_api_v2/generate_scan_sign_qrcode') . '?' . $queryStr;
        } else {
            $ret['qrcodeUrl'] = '';
        }

        // 班级名称限制最长46个字符
        if(strlen($ret['className']) > 46) {
            $ret['className'] = substr($ret['className'], 0, 46) . '...';
        }

        exit(json("", true, $ret));
    }

    // 检查当前课程信息
    public function check_brand_is_exist($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);

        // if($this->get('address')){
        //     $str = md5(strrev($this->get('address')));
        //     $update = array(
        //         'license_code_address' => $str
        //     );
        //     $this->db->update(classesModel::$brandTable, $update, "id='{$brandId}'");
        // }
       
        exit(json('', true, array(
            'is_exist' => $brandInfo ? true : false
        )));
    }

    // 获取班级通知和校园公告(混排，前10条)
    public function get_class_notify_data($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        // 获取前10条班级通知
        $notifyParams['isDelete'] = 0;
        $notifyParams['classId'] = $brandInfo['class_id'];
        $notifyParams['pageStart'] = 0;
        $notifyParams['pageSize'] = 10;
        $notifyParams['field'] = 'id, notify_title as title, updatetime as time, notify_type as notifyType, external_link as externalLink, notify_urgent as notifyUrgent, urgent_endtime as urgentEndtime, is_top as isTop';
        $notifyParams['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $notifyParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $notifys = $this->contentModel->get_notify_list($notifyParams);

        // 获取前10条校园公告
        $announceParams['schoolId'] = $brandInfo['school_id'];
        $announceParams['isDelete'] = 0;
        $announceParams['pageStart'] = 0;
        $announceParams['pageSize'] = 10;
        $announceParams['field'] = 'id, announce_title as title, updatetime as time, announce_type as announceType, external_link as externalLink, is_top as isTop';
        $announceParams['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $announceParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $announces = $this->contentModel->get_announce_list($announceParams);

        // 班级通知和校园公告混排
        $topDataArr = array();
        $notTopDataArr = array();
        $notifyAndAnnounceArr = array();
        if(!empty($notifys) || !empty($announces)) {
            foreach($notifys as $notify) {
                $tempArr['cateType'] = 'notify';
                $tempArr['id'] = $notify['id'];
                $tempArr['title'] = $notify['title'];
                $tempArr['time'] = $notify['time'];
                $tempArr['isTop'] = $notify['isTop'] ? true : false;
                $tempArr['contentType'] = $notify['notifyType'];
                $tempArr['externalLink'] = $notify['externalLink'];
                $tempArr['notifyUrgent'] = $notify['notifyUrgent'];
                $tempArr['urgentEndtime'] = $notify['urgentEndtime'];
                if($tempArr['isTop']) {
                    array_push($topDataArr, $tempArr);
                } else {
                    array_push($notTopDataArr, $tempArr);
                }
            }
            foreach($announces as $announce) {
                $tempArr['cateType'] = 'announce';
                $tempArr['id'] = $announce['id'];
                $tempArr['title'] = $announce['title'];
                $tempArr['time'] = $announce['time'];
                $tempArr['isTop'] = $announce['isTop'] ? true : false;
                $tempArr['contentType'] = $announce['announceType'];
                $tempArr['externalLink'] = $announce['externalLink'];
                $tempArr['notifyUrgent'] = '0';
                $tempArr['urgentEndtime'] = '';
                if($tempArr['isTop'] == 1) {
                    array_push($topDataArr, $tempArr);
                } else {
                    array_push($notTopDataArr, $tempArr);
                }
            }
            // 按时间排序
            $timeKey =  array_column($topDataArr, 'time');
            array_multisort($timeKey, SORT_DESC, $topDataArr);
            // 按时间排序
            $timeKey =  array_column($notTopDataArr, 'time');
            array_multisort($timeKey, SORT_DESC, $notTopDataArr);
            // 合并，获取前10项
            $notifyAndAnnounceArr = array_merge($topDataArr, $notTopDataArr);
            if(count($notifyAndAnnounceArr) > 10) {
                $notifyAndAnnounceArr = array_slice($notifyAndAnnounceArr, 0, 10);
            }
            // echo '<pre>';var_export($notifyAndAnnounceArr);exit;
        }

        exit(json("", true, $notifyAndAnnounceArr));
    }

    // 获取校园公告详情
    public function get_announce_info($brandId, $announceId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));

        // 获取通知详情
        $info = $this->contentModel->get_announce_info($announceId);
        if(!$info) throw new Exception("内容不存在");
        // 返回值
        $ret['id'] = $info['id'];
        $ret['title'] = $info['announce_title'];
        $ret['content'] = trim_link_tags(urlencode($info['announce_content']));
        $ret['time'] = substr($info['updatetime'], 0, 16);
        $ret['announceType'] = $info['announce_type'];
        $ret['externalLink'] = $info['external_link'];
        exit(json("", true, $ret));
    }

    // 获取班牌今天食谱列表
    public function get_brand_recipe_list($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取食谱
        $recipeParams['schoolId'] = $brandInfo['school_id'];
        $recipeParams['campusId'] = $brandInfo['campus_id'];
        $recipeParams['classId'] = $classInfo['id'];
        //过滤软删除
        $recipeParams['isDelete'] = 0;
        $recipeList = $this->dataModel->get_recipe_list($recipeParams);
        // 获取菜品分类列表
        $cateParams['schoolId'] = $brandInfo['school_id'];
        $cateParams['campusId'] = $brandInfo['campus_id'];
        $cateParams['isDelete'] = 0;
        $cateList = $this->dataModel->get_recipe_cate_list($cateParams);
        // 使用id作为键值
        $cateList = array_value_to_key($cateList, 'id');
        $ret = array();
        if($recipeList) {
            // 如存在多个，获取一个
            $recipe = $recipeList[0];
            // 获取食谱时段
            $timeArr = json_decode($recipe['time_json'], true);
            if($timeArr) {
                // 获取食谱详情
                $detailParams['schoolId'] = $brandInfo['school_id'];
                $detailParams['campusId'] = $brandInfo['campus_id'];
                $detailParams['recipeId'] = $recipe['id'];
                $detailParams['week'] = date('w') == '0' ? '7' : date('w'); // 周日菜品week为7
                $detailParams['isDelete'] = 0;
                // 按timeslot排序
                $detailParams['orderBy'] = array(
                    'order' => 'timeslot',
                    'sort' => 'ASC'
                );
                $detailList = $this->dataModel->get_recipe_detail_list($detailParams);

                foreach($detailList as $detail) {
                    if($detail['content']) {
                        $contentArr = json_decode($detail['content'], true);
                        if($contentArr) {
                            if(isset($timeArr[$detail['timeslot'] - 1])) {
                                $beginTime = $timeArr[$detail['timeslot'] - 1]['begin_time'] . ':00';
                                $endTime = date("H:i", strtotime($timeArr[$detail['timeslot'] - 1]['end_time']) - 60) . ':59';
                                // 获取菜品分类名称
                                foreach($contentArr as $key => $item) {
                                    $contentArr[$key]['cateName'] = isset($cateList[$item['cate_id']]) ? $cateList[$item['cate_id']]['title'] : '';
                                    unset($contentArr[$key]['cate_id']);
                                }
                                $tempArr = array(
                                    'beginTime' => $beginTime,
                                    'endTime' => $endTime,
                                    'content' => $contentArr
                                );
                                array_push($ret, $tempArr);
                            }
                           
                        }
                    }
                }
            }
        }
        // var_dump(date('w'));exit;
        // 返回值
        exit(json("", true, $ret));
    }
    // 更新教师卡号
    public function update_teacher_cardnum($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->post("teacher_id"))) {
            throw new Exception('教师id不能为空');
        }
        if(empty(trim($this->post("cardnum")))) {
            throw new Exception('卡号不能为空');
        }
        $teacherId = $this->post("teacher_id");
        $teacherInfo = $this->schoolModel->get_school_user_info($teacherId);
        if(empty($teacherInfo)) {
            throw new Exception('教师id不存在');
        }
        if($teacherInfo['school_id'] != $brandInfo['school_id']) {
            throw new Exception('教师id不存在');
        }
        $cardNum = trim($this->post("cardnum"));
        // 学校内学生物理卡号唯一
        $existStudent = $this->schoolModel->get_student_info_by_realcard($cardNum, $teacherInfo['school_id'], 0);
        if(!empty($existStudent)) {
            throw new Exception('物理卡号已被学生占用');
        }
        // 学校内教师物理卡号唯一
        $existTeacher = $this->schoolModel->get_teacher_info_by_realcard($cardNum, $teacherInfo['school_id'], $teacherId);
        if(!empty($existTeacher)) {
            throw new Exception('物理卡号已被教师占用');
        }
        // 更新卡号
        $update['realcard'] = $cardNum;
        $update['updatetime'] = date('Y-m-d H:i:s');
        $this->db->update(SchoolModel::$schoolUserTable, $update, "id='{$teacherId}'");

        // 返回成功提示和头像地址
        exit(json("卡号更新成功", true));
    }
}